<template>
  <!--  不合格-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="单号">
          <el-input v-model="searchParam.no" placeholder="请输入单号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="来源单号">
          <el-input v-model="searchParam.sourceNo" placeholder="请输入来源单号" clearable style="width: 200px" />
        </el-form-item>
        <!--        <el-form-item label="质检方案名称">-->
        <!--          <el-input v-model="searchParam.name" placeholder="请输入质检方案名称" clearable style="width: 200px"/>-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch()">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息 </div>
        <div class="pageTableButView">
          <!-- <el-button :icon="Plus" @click="handleAdd()">新建</el-button> -->
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 320px)">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            <!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 --> {{ (pageSearch.current - 1) * pageSearch.pageSize +
              scope.$index + 1 }} </template>
        </el-table-column>
        <el-table-column prop="no" label="单号" align="center" min-width="200" />
        <el-table-column prop="sourceNo" label="来源单号" align="center" min-width="200" />
        <el-table-column prop="materialName" label="物料名称" align="center" min-width="200" />
        <el-table-column prop="qualityPlanName" label="质检方案名称" align="center" min-width="200" show-overflow-tooltip />
        <el-table-column prop="qualityType" label="质检类型" align="center" min-width="200">
          <template #default="scope">
            <span> {{ getQualityTypeByValue(scope.row.qualityType) }} </span></template>
        </el-table-column>
        <el-table-column prop="failQuantity" label="不合格数" align="center" min-width="100" show-overflow-tooltip />
        <el-table-column prop="qualityRemark" label="备注" align="center" min-width="200" show-overflow-tooltip />
				<el-table-column prop="createTime" label="创建时间" align="center" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" align="center" fixed="right" width="180">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row, 1)" v-if="!scope.row.activate" type="text" size="small"
              :icon="Edit"> 审批 </el-button>
            <el-button @click="handleEdit(scope.row, 0)" v-if="scope.row.activate" type="text" size="small"
              :icon="Tickets"> 审批详情 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current" v-model:page-size="pageSearch.pageSize"
          :page-sizes="[10, 20, 50, 100, 200, 500]" layout="total, sizes, prev, pager, next" :total="pageTotal"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <!-- 弹窗表单 -->
    <el-dialog v-model="showCrud" :title="crudTitle" width="1000px">
      <el-form :model="formData" label-width="90px" ref="ruleFormRef" :rules="rules" class="demo-ruleForm">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="返工数量" prop="reworkQuantity">
              <el-input-number v-model="formData.reworkQuantity" :step="1" step-strictly :min="0" v-if="isEdit" />
              <div v-else> {{ formData.reworkQuantity }} </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报废数量" prop="auditorScrapQuantity">
              <el-input-number v-model="formData.auditorScrapQuantity" :step="1" step-strictly :min="0" v-if="isEdit" />
              <div v-else> {{ formData.auditorScrapQuantity }} </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合格数量" prop="auditorPassQuantity">
              <el-input-number v-model="formData.auditorPassQuantity" :step="1" step-strictly :min="0" v-if="isEdit" />
              <div v-else> {{ formData.auditorPassQuantity }} </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item required label="审批人" prop="auditorId">
              <el-select v-model="formData.auditorId" placeholder="请选择审批人" clearable filterable v-if="isEdit">
                <el-option v-for="item in userOptions" :key="item.id" :label="item.nickname"
                  :value="item.id"></el-option>
              </el-select>
              <div v-else> {{ formData.auditorName }} </div>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注" prop="auditorRemark">
              <el-input v-model="formData.auditorRemark" style="width: 718px" :rows="3" type="textarea"
                placeholder="请输入备注" v-if="isEdit" />
              <div v-else> {{ formData.auditorRemark }} </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" v-if="isEdit" @click="handleSave(ruleFormRef)">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useEquipmentData } from '@/hooks/baseData/equipment';
import axiosInstance from '@/utils/http/api';
import { Delete, Edit, Search, Tickets, Upload, Refresh, Plus, DocumentCopy } from '@element-plus/icons-vue'

onMounted(() => {
  handleSearch()
  getMaterial()
  getQualityPlanList()
})

const qualityPlanList = ref({})

const getQualityPlanList = () => {
  axiosInstance.post('/api/basedataQualityScheme/getAll', {})
    .then(res => {
      if (res.code !== 200) {
        ElMessage.error(res.message);
        return false
      }
      qualityPlanList.value = res.data
    });
}


const pageSearch = ref({
  current: 1,
  pageSize: 10
})

const schemeTaskForm = ref({})

const configTableShow = ref(false)


// 配置质检项表
const configTable = ref([])

// 可适用物料
const materialTable = ref([])


const rowInfo = ref({})


const materialList = ref([])
const userOptions = ref([])
const getMaterial = () => {
  axiosInstance.post('/api/basedataMaterial/getAll', {})
    .then(res => {
      materialList.value = res.data
    })

  axiosInstance.post('/api/basedataUser/getAll', {})
    .then(res => {
      userOptions.value = res.data
    })

}



// 通用更新接口函数
const handleUpdateQualityScheme = (updatedRowInfo) => {
  axiosInstance.put('/api/qualitySchemeTask/update', updatedRowInfo).then(res => {
    if (res.code != 200) {
      ElMessage.error(res.message);
      return false;
    }
    ElMessage.success('操作成功!');
    // showConfig.value = false;
    // showMaterial.value = false
    configTableShow.value = false
    // 刷新配置质检项列表
    // handleConfigEdit(rowInfo.value);
    handleSearch();
  });
};



const pageTotal = ref(null)//页面总数
const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框
const searchParam = ref({})//页面检索条件
const showConfig = ref(false)
const configData = ref({})
const crudTitle = computed(() => {
  return isEdit.value ? '审批' : '详情';
});//弹出层标题
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

// 质检方式
const qualityWayList = reactive([
  {
    label: '全检',
    value: '1'
  }, {
    label: '比例抽检',
    value: '2'
  }, {
    label: '固定抽检',
    value: '3'
  }, {
    label: '自定义抽检',
    value: '4'
  }
])


// 判断质检类型
const getQualityTypeByValue = (e) => {
  let name = null
  for (const item of qualityTypeList) {
    if (e == item.value) {
      name = item.label
    }
  }
  return name
}

// 质检类型
const qualityTypeList = reactive([
  {
    label: '首件检',
    value: '1',
    type: 'material'
  },
  {
    label: '末件检',
    value: '2',
    type: 'material'
  },
  {
    label: '生产',
    value: '3',
    type: 'material'
  },
  {
    label: '巡检',
    value: '4',
    type: 'material'
  },
  {
    label: '入库检',
    value: '5',
    type: 'procedure'
  },
  {
    label: '出库检',
    value: '6',
    type: 'procedure'
  },
  {
    label: '来料检',
    value: '7',
    type: 'procedure'
  },
  // 继续添加更多检查类型...
]);

const ruleFormRef = ref<FormInstance>()

interface RuleForm {
  name: string
  code: string
  qualityWay: string
  proportionNumber: string
  qualityNumber: string
  qualityType: string
  qualityInterval: number
  qualityIsLive: boolean
  qualityRemark: string
  qualityJson: string
}




let formData = ref({})


const rules = reactive<FormRules<formData>>({
  auditorId: [
    { required: true, message: '请选择审批人', trigger: 'blur' },
  ],
})


// const paginatedData = reactive([])//列表数据
const paginatedData = ref<RuleForm[]>([]);

// 获取列表接口
const handleSearch = () => {
  axiosInstance.post('/api/qualitySchemeTask/getPage', {
    ...searchParam.value,
    ...pageSearch.value,
    ...{
      status: true,
      selectUnQualified: true
    }
  })
    .then(res => {
      if (res.code !== 200) {
        ElMessage.error(res.message);
        return false
      }
      const loop = JSON.parse(JSON.stringify(res.data.records));
      const dataLoop = loop.map(item => {
        const list = JSON.parse(item.qualityJson);
        return {
          ...item,
          ...list,
          id: item.id,
          qualityPlanName: list.name, // 替换或添加新的属性
          statusShow: item.status, // 如果list中没有statusShow，或者需要使用item中的status，则可以保留这一行
        };
      });
      paginatedData.value = dataLoop;

      pageTotal.value = res.data.total
    });
}

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e
  handleSearch()
}

const handleCurrentChange = (e) => {
  pageSearch.value.current
  handleSearch()
}

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  pageSearch.value.current = 1
  // current.value = 1
  handleSearch();
};


// 编辑
const handleEdit = (row: any, type) => {
  // 1 审批 0 详情
  isEdit.value = type == 1 ? true : false
  if (isEdit.value == true) {
    formData.value = { id: row.id, auditorId: JSON.parse(localStorage.getItem('userVO'))?.team?.userPersonId }
  } else {
    console.log(row);
    formData.value = row
  }
  showCrud.value = true;
};


// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
  if (!e) return
  await e.validate((valid, fields) => {
    if (valid) {
      formData.value.auditorName = userOptions.value.find(item => item.id == formData.value.auditorId).userName
      axiosInstance.post('/api/qualitySchemeTask/auditor', formData.value).then(res => {
        if (res.code != 200) {
          ElMessage.error(res.message)
          return false
        }
        ElMessage.success('操作成功!')
        showCrud.value = false;
        handleSearch();
      })

    }
  })
}

</script>
<style scoped></style>
